package com.imooc.bilibili.aspect;

import com.imooc.bilibili.annotation.ApiLimitedRoleAnnotation;
import com.imooc.bilibili.entity.RoleInfo;
import com.imooc.bilibili.entity.UserRoleRelation;
import com.imooc.bilibili.exception.ConditionException;
import com.imooc.bilibili.service.UserRoleService;
import com.imooc.bilibili.support.UserSupport;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Order(1)
@Aspect
@Component
public class ApiLimitedRoleAspect {

    @Autowired
    private UserSupport userSupport;

    @Autowired
    private UserRoleService userRoleService;

    @Pointcut("@annotation(com.imooc.bilibili.annotation.ApiLimitedRoleAnnotation)")
    public void check() {
    }

    @Before("check() && @annotation(apiLimitRole)")
    public void doBefore(JoinPoint joinPoint, ApiLimitedRoleAnnotation apiLimitRole) {
        Long userId = userSupport.getCurrnetUserId().get("userId");
        List<UserRoleRelation> userRoleList = userRoleService.getUserRoleByUserId(userId);
        List<String> roleCodes = new ArrayList<>();
        userRoleList.stream().forEach(relation -> {
            RoleInfo roleInfo = relation.getRoleInfo();
            String code = roleInfo.getRoleCode();
            if (!roleCodes.contains(code)) {
                roleCodes.add(code);
            }
        });

        String[] limitedRoleCodeList = apiLimitRole.limitedRoleCodeList();
        List<String> limitedRoleCodes = Arrays.stream(limitedRoleCodeList).distinct().collect(Collectors.toList());
        roleCodes.retainAll(limitedRoleCodes);
        if (!roleCodes.isEmpty()) {
            throw new ConditionException("权限不足！");
        }
    }
}
